import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style

NProgress.configure({ showSpinner: false })// NProgress Configuration

// permission judge function 权限判定功能
// function hasPermission(perms, permissions) {
//   if (perms.indexOf('*') >= 0) return true // admin permission passed directly
//   if (!permissions) return true
//   return perms.some(perm => permissions.indexOf(perm) >= 0)
// }

const whiteList = ['/login', '/auth-redirect', '/register', '/register-success', '/active-success', '/shop-info']// no redirect whitelist无重定向白名单

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  store.dispatch('GetUserInfo').then(res => {
    const perms = res.perms
    if (!store.getters.routerLoadDone) {
      store.dispatch('GenerateRoutes', { perms }).then(() => { // 根据perms权限生成可访问的路由表
        router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
        router.options.routes = store.getters.routers
      })
    }
    if (res.status !== 0) {
      if (to.path === '/') {
        next()
        NProgress.done()
      } else if (to.path === '/dashboard') {
        next()
        NProgress.done
      } else {
        next({ path: '/' })
        NProgress.done()
      }
    } else if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      next()
      NProgress.done()
    }
  }).catch(() => {
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
      NProgress.done()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  })
})

router.afterEach(() => {
  NProgress.done() // finish progress bar完成进度条
})
